import time
from datetime import datetime, timedelta

from flask import session, redirect, url_for, request, render_template, current_app, jsonify, g, abort

# 后台登录
from info.constants import ADMIN_USER_PAGE_MAX_COUNT
from info.models import User
from info.modules.admin import admin_blu
from info.utils.common import user_login_data

@admin_blu.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        user_id = session.get('user_id')
        is_admin = session.get('is_admin')
        if user_id and is_admin:
            return redirect(url_for('admin.index'))
        return render_template('admin/login.html')

    username = request.form.get('username')
    password = request.form.get('password')

    if not all([username,password]):
        return render_template('admin/login.html', errmsg = '参数不足')

    # 取出管理员数据
    try:
        user = User.query.filter(User.mobile==username, User.is_admin==True).first()
    except BaseException as  e:
        current_app.logger.error(e)
        return render_template('admin/login.html', errmsg='数据操作错误')

    if not user:
        return render_template('admin/login.html', errmsg='管理员不存在')

    if not user.check_password(password):
        return render_template('admin/login.html', errmsg='帐号或密码错误')

    session['user_id'] = user.id
    session['is_admin'] = True

    return redirect(url_for('admin.index'))


@admin_blu.route('/index')
@user_login_data
def index():

    return render_template("admin/index.html", user=g.user.to_dict())


@admin_blu.route('/user_count')
def user_count():
    total_count = 0

    try:
        total_count = User.query.filter(User.is_admin == False).count()
    except BaseException as e:
        current_app.logger.error(e)

    mon_count=0
    t = time.localtime()
    mon_date_str = '%d-%02d-01'%(t.tm_year,t.tm_mon)
    mon_date = datetime.strptime(mon_date_str, '%Y-%m-%d')

    try:
        mon_count = User.query.filter(User.is_admin == False, User.create_time >= mon_date).count()
    except BaseException as e:
        current_app.logger.error(e)

    day_count =0
    t = time.localtime()
    day_date_str = '%d-%02d-%02d' % (t.tm_year, t.tm_mon, t.tm_mday)
    day_date = datetime.strptime(day_date_str, '%Y-%m-%d')

    try:
        day_count = User.query.filter(User.is_admin == False, User.create_time >= day_date).count()
    except BaseException as e:
        current_app.logger.error(e)

    active_count = []
    active_time = []
    # 获取某日的注册人数　　注册时间　>= 当日０点　< 次日０点
    for i in range(0,30):
        begin_date = day_date - timedelta(days=i)
        end_date = day_date + timedelta(days=1) - timedelta(days=i)
        try:
            one_day_count = User.query.filter(User.is_admin == False, User.create_time >= begin_date, User.create_time < end_date ).count()
            active_count.append(one_day_count)

            one_day_str = begin_date.strftime('%Y-%m-%d')
            active_time.append(one_day_str)
        except BaseException as e:
            current_app.logger.error(e)

    active_time.reverse()
    active_count.reverse()

    data={
        'total_count': total_count,
        'mon_count': mon_count,
        'day_count': day_count,
        'active_count':active_count,
        'active_time':active_time

    }
    return render_template('admin/user_count.html', data=data)


# 用户列表
@admin_blu.route('/user_list')
def user_list():
    p = request.args.get('p', 1)

    try:
        p = int(p)
    except BaseException as e:
        current_app.logger.error(e)
        return abort(403)

    try:
        pn = User.query.filter(User.is_admin == False).paginate(p, ADMIN_USER_PAGE_MAX_COUNT)

    except BaseException as e:
        current_app.logger.error(e)
        return abort(500)

    data = {
        'user_list': [user.to_admin_dict() for user in pn.items],
        'total_page': pn.pages,
        'cur_page': pn.page
    }

    return render_template('admin/user_list.html', data=data)


# 退出登录
@admin_blu.route('/logout')
def logout():
    session.pop('user_id', None)
    session.pop('is_admin', None)
    return redirect(url_for('admin.login'))